<template>
  <div>
    <div class="container">
      <div class="uploadvideo">
        <div class="uploadvideo_left">
          <div class="uploadvideo_item">
            <div class="filebox">
              <input type="file" id="fileUpload" @change="fileChange($event)" class="filebtn" />
              <div class="flletit">选择视频</div>
            </div>
            <div class="filetitle">{{ fileTitle }}</div>
          </div>
          <div class="uploadvideo_item">
            <span>上传状态</span>
            <div class="filetitle">{{ statusText }}</div>
          </div>
          <div class="upload-type">
            <el-button slot="trigger" size="small" type="primary" @click="authUpload" :disabled="uploadDisabled">开始上传</el-button>
            <el-button style="margin-left: 10px" size="small" type="danger" @click="pauseUpload" :disabled="pauseDisabled">暂停</el-button>
            <el-button slot="trigger" size="small" type="success" :disabled="resumeDisabled" @click="resumeUpload">恢复上传</el-button>

            <el-button size="small" type="danger" @click="emitEvent('', '')">删除</el-button>
          </div>
        </div>
        <div class="uploadvideo_right">
          <div class="uploadvideo_right_video">
            <video v-show="pro_src != ''" style="width: 100%" controls="controls" id="my_video" :src="pro_src"></video>
          </div>
        </div>
      </div>
      <el-progress :text-inside="true" :stroke-width="15" :percentage="authProgress"></el-progress>
    </div>
    <!-- <div class="tc">
        请在谷歌或者360浏览器<span style="color:red">极速模式</span>中打开
    </div> -->
  </div>
</template>
<script>
// import kitx from "kitx";
function isIE () {
  //是否为ie浏览器?
  if (window.ActiveXObject || "ActiveXObject" in window) {
    return true;
  } else {
    return false;
  }
}
var kitx = {};
if (!isIE()) {
  kitx = require("kitx");
}


import axios from "axios";

import { mapState } from "vuex";
export default {
  data () {
    return {
      BASEURL: "",
      video_url: "",
      vid: "",
      video_pic: "",
      fileTitle: "",
      timeout: "",
      partSize: "",
      parallel: "",
      retryCount: "",
      retryDuration: "",
      region: "cn-shanghai",
      userId: "1916570388667663",
      file: null,
      authProgress: 0,
      uploadDisabled: true,
      resumeDisabled: true,
      pauseDisabled: true,
      uploader: null,
      statusText: "",
    };
  },
  computed: {
    ...mapState({
      plugin: (state) => state.plugin,
    }),
  },
  props: {
    types: {
      type: String,
      default: "video",
    },
    pro_src: {
      type: String,
      default: "",
    },
  },
  created () {
    this.$store.dispatch("getPlugin");
    this.$api.getSettings.findConfig({ iden: "video_url" }).then(res => {
      if (res.data.code == 200) {
        this.BASEURL = res.data.result;
      }
    })
  },
  methods: {
    isIE () {
      //是否为ie浏览器?
      if (window.ActiveXObject || "ActiveXObject" in window) {
        return true;
      } else {
        return false;
      }
    },
    close_video () {
      //视频暂停
      this.video_url = "";
      this.vid = "";
      this.statusText = "";
      this.fileTitle = "";
      document.getElementById("my_video").pause();
    },
    emitEvent (obj) {
      this.$emit("send_url", obj);

      this.vid = "";
      this.statusText = "";
      this.fileTitle = "";
    },
    get_plublic (parm) {
      //获取上传凭证
      return new Promise((resove, reject) => {
        var url = "";
        if (parm.Action == 'CreateUploadVideo') {
          url = `${window.location.origin}/api/common/applets_pay/getToken`
        } else if (parm.Action == 'RefreshUploadVideo') {
          url = `${window.location.origin}/api/common/applets_pay/refresh`
        }
        axios.get(url, { params: parm }).then(res => {
          if (res.data.code == 200) {
            resove(res.data.result)
          } else {
            this.$fnc.alertError('获取凭证错误')
          }
        })
      })
    },

    emitEventVod () {
      this.authProgress = 0;
      this.fileTitle = "";
      this.statusText = "";
      this.pauseDisabled = true;
      this.resumeDisabled = true;
      this.uploadDisabled = true;
    },
    fileChange (e) {
      if (this.plugin && this.plugin.yspdb && this.plugin.yspdb.is_open == 1) {
        this.file = e.target.files[0];
        console.log(this.file);
        if (!this.file) {
          this.$fnc.alertError("请先选择需要上传的文件!");
          return;
        }
        if (this.types == 'video') {
          if (this.file.type !== "video/mp4") {
            this.$fnc.alertError("请选择.mp4文件!");
            return;
          }
        } else if (this.types == 'mp3') {
          if (this.file.type !== "audio/mpeg" && this.file.type !== "audio/mp3") {
            this.$fnc.alertError("请选择.mp3文件!");
            return;
          }
        }

        this.fileTitle = this.file.name;
        var userData = '{"Vod":{}}';
        if (this.uploader) {
          this.uploader.stopUpload();
          this.authProgress = 0;
          this.statusText = "";
        }
        this.uploader = this.createUploader();
        this.uploader.addFile(this.file, null, null, null, userData);
        this.uploadDisabled = false;
        this.pauseDisabled = true;
        this.resumeDisabled = true;
      } else {
        this.$fnc.alertError("上传失败，请先开通音视频服务器");
      }
    },
    authUpload () {
      // 然后调用 startUpload 方法, 开始上传
      if (this.uploader !== null) {
        this.uploader.startUpload();
        this.uploadDisabled = true;
        this.pauseDisabled = false;
      }
    },
    // 暂停上传
    pauseUpload () {
      if (this.uploader !== null) {
        this.uploader.stopUpload();
        this.resumeDisabled = false;
        this.pauseDisabled = true;
      }
    },
    // 恢复上传
    resumeUpload () {
      if (this.uploader !== null) {
        this.uploader.startUpload();
        this.resumeDisabled = true;
        this.pauseDisabled = false;
      }
    },
    createUploader () {
      let self = this;
      // eslint-disable-next-line no-undef
      let uploader = new AliyunUpload.Vod({
        timeout: self.timeout || 60000,
        partSize: self.partSize || 1048576,
        parallel: self.parallel || 5,
        retryCount: self.retryCount || 3,
        retryDuration: self.retryDuration || 2,
        region: self.region,
        userId: self.userId,
        // 添加文件成功
        addFileSuccess: function () {
          self.uploadDisabled = false;
          self.resumeDisabled = false;
          self.$fnc.alertSuccess({ text: "添加文件成功" });
        },
        // 开始上传
        onUploadstarted: function (uploadInfo) {
          // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
          if (!uploadInfo.videoId) {
            //不存在
            let title = uploadInfo.file.name.substr(
              0,
              uploadInfo.file.name.lastIndexOf(".")
            );
            let params = {};
            params.Action = "CreateUploadVideo";
            params.title = title;
            params.fileName = uploadInfo.file.name;
            self.get_plublic(params).then(data => {
              let uploadAuth = data.UploadAuth; //	上传凭证。
              let uploadAddress = data.UploadAddress; //上传地址。
              let videoId = data.VideoId; //	视频ID
              self.vid = data.VideoId;
              uploader.setUploadAuthAndAddress(
                uploadInfo,
                uploadAuth,
                uploadAddress,
                videoId
              );
            })
            self.statusText = "文件开始上传...";
          } else {
            // 如果videoId有值，根据videoId刷新上传凭证
            let params = {};
            params.Action = "RefreshUploadVideo";
            params.VideoId = uploadInfo.videoId;
            self.get_plublic(params).then(data => {
              let uploadAuth = data.UploadAuth; //	上传凭证。
              let uploadAddress = data.UploadAddress; //上传地址。
              let videoId = data.VideoId; //	视频ID
              self.vid = data.VideoId;
              uploader.setUploadAuthAndAddress(
                uploadInfo,
                uploadAuth,
                uploadAddress,
                videoId
              );
            })
          }
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {

          self.$set(
            self,
            "video_pic",
            `${self.BASEURL}/snapshot/${uploadInfo.videoId}00001.jpg`
          );
          self.video_url = `${self.BASEURL}/${uploadInfo.object}`;
          var obj = {
            video_url: self.video_url,
            video_pic: self.video_pic,
            video_id: uploadInfo.videoId,
          };
          //   self.emitEvent(self.video_url, self.video_pic);
          self.emitEvent(obj);
          self.statusText = "文件上传成功!";
        },
        // 文件上传失败
        onUploadFailed: function () {
          self.statusText = "文件上传失败!";
        },
        // 取消文件上传
        onUploadCanceled: function () {
          self.statusText = "文件已暂停上传";
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function (uploadInfo, totalSize, progress) {
          let progressPercent = Math.ceil(progress * 100);
          self.authProgress = progressPercent;
          self.statusText = "文件上传中...";
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo) {
          // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
          // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
          // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
          let params = {};
          params.Action = "RefreshUploadVideo";
          params.VideoId = uploadInfo.videoId;
          self.get_plublic(params).then(data => {
            let uploadAuth = data.UploadAuth; //	上传凭证。
            self.vid = data.VideoId;
            uploader.resumeUploadWithAuth(uploadAuth);
          })
          self.statusText = "文件超时...";
        },
        // 全部文件上传结束
        onUploadEnd: function () {
          self.$fnc.alertSuccess({ text: "文件上传完毕" });
          self.statusText = "文件上传完毕";
        },
      });
      return uploader;
    },

    timestamp () {
      var date = new Date();
      var YYYY = date.getUTCFullYear();
      var MM = kitx.pad2(date.getUTCMonth() + 1);
      var DD = kitx.pad2(date.getUTCDate());
      var HH = kitx.pad2(date.getUTCHours());
      var mm = kitx.pad2(date.getUTCMinutes());
      var ss = kitx.pad2(date.getUTCSeconds());
      // 删除掉毫秒部分
      return `${YYYY}-${MM}-${DD}T${HH}:${mm}:${ss}Z`;
    },
    canonicalize (normalized) {
      var fields = [];
      for (var i = 0; i < normalized.length; i++) {
        var [key, value] = normalized[i];
        fields.push(key + "=" + value);
      }
      return fields.join("&");
    },
    encode (str) {
      var result = encodeURIComponent(str);
      return (
        result
          // eslint-disable-next-line no-useless-escape
          .replace(/\!/g, "%21")
          // eslint-disable-next-line no-useless-escape
          .replace(/\'/g, "%27")
          .replace(/\(/g, "%28")
          .replace(/\)/g, "%29")
          .replace(/\*/g, "%2A")
      );
    },
    replaceRepeatList (target, key, repeat) {
      for (var i = 0; i < repeat.length; i++) {
        var item = repeat[i];

        if (item && typeof item === "object") {
          const keys = Object.keys(item);
          for (var j = 0; j < keys.length; j++) {
            target[`${key}.${i + 1}.${keys[j]}`] = item[keys[j]];
          }
        } else {
          target[`${key}.${i + 1}`] = item;
        }
      }
    },
    flatParams (params) {
      var target = {};
      var keys = Object.keys(params);
      for (let i = 0; i < keys.length; i++) {
        var key = keys[i];
        var value = params[key];
        if (Array.isArray(value)) {
          this.replaceRepeatList(target, key, value);
        } else {
          target[key] = value;
        }
      }
      return target;
    },
    normalize (params) {
      var list = [];
      var flated = this.flatParams(params);
      var keys = Object.keys(flated).sort();
      for (let i = 0; i < keys.length; i++) {
        var key = keys[i];
        var value = flated[key];
        list.push([this.encode(key), this.encode(value)]); //push []
      }
      return list;
    },
  },
  watch: {
    pro_src () {
      document.getElementById("my_video").play();
    },
  },
};
</script>
<style>
.filebox {
  /* display: flex;
  justify-content: flex-start;
  align-items: center; */
}
.upload > div:nth-of-type(1) {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.container {
  text-align: center;
  line-height: 1;
}
.upload-type {
  width: 100%;
  display: flex;
  margin: 10px 0;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}
.filebox {
}
.filebox .filebtn {
  width: 100%;
  height: 100%;
  border: none;
  background: none;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
}
.filebox .flletit {
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
}
.uploadvideo {
  width: 90%;
  height: 90%;
  display: flex;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}
.filebox {
  width: 100px;
  height: 32px;
  color: #fff;
  background-color: #17b3a3;
  border-color: #17b3a3;
  position: relative;
  border-radius: 3px;
  text-align: center;
  line-height: 32px;
}
.flletit {
  font-size: 14px;
}
.filetitle {
  font-size: 14px;
  color: #000000;
  float: left;
  padding-left: 20px;
}
.uploadvideo_left {
  width: 50%;
}

.uploadvideo_item {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 10px 0;
}
.uploadvideo_item span {
  font-size: 14px;
  width: 100px;
  height: 32px;
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
  position: relative;
  border-radius: 3px;
  text-align: center;
  line-height: 32px;
}
.status {
  width: 100px;
  height: 32px;
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
}
.uploadvideo_right {
  width: 50%;
}
.uploadvideo_right_video {
  width: 100%;
  background-color: #000000;
  height: 80%;
}
.el-progress {
  position: absolute;
  line-height: 1;
  bottom: 10px;
  width: 90%;
}
</style>
